package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"pet-manager/cache"
	"pet-manager/jwt"
	"pet-manager/models"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账户或密码不能为空",
		})
		return
	}

	redis_key := "pet_login" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()

	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码登录超过三次，禁止登录",
		})
		return
	}

	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "没有找到该账户",
		})
		return
	}

	if user.Password != jwt.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误,封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}

func PetAdd(c *gin.Context) {
	name := c.PostForm("name")
	content := c.PostForm("content")
	kind := c.PostForm("kind")
	if name == "" || content == "" || kind == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	data := models.Pet{
		Name:    name,
		Content: content,
		Kind:    kind,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	redis_key := "pet_add_" + strconv.Itoa(int(data.ID))
	var pet models.Pet
	models.DB.Where("id = ?", data.ID).First(&pet)
	jsonData, _ := json.Marshal(pet)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func PetList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var pet []models.Pet

	redis_key := "pet_list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Order("id DESC").Offset(offset).Limit(size).Find(&pet)
		jsonData, _ := json.Marshal(pet)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &pet)
	}

	var total int64
	models.DB.Model(&models.Pet{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表展示成功",
		"total": total,
		"data":  pet,
	})
	return

}

func PetDel(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))

	var pet models.Pet
	models.DB.Where("id = ?", id).Delete(&pet)

	redis_key := "pet_del_" + strconv.Itoa(id)
	cache.Rdb.Del(cache.Ctx, redis_key)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return

}

func UpPet(c *gin.Context) {
	id, _ := strconv.Atoi(c.PostForm("id"))
	name := c.PostForm("name")
	content := c.PostForm("content")
	kind := c.PostForm("kind")
	if name == "" || content == "" || kind == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	data := models.Pet{
		Name:    name,
		Content: content,
		Kind:    kind,
	}

	err := models.DB.Where("id = ?", id).Updates(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "编辑失败",
		})
		return
	}

	redis_key := "pet_up_" + strconv.Itoa(int(data.ID))
	var pet models.Pet
	models.DB.Where("id = ?", data.ID).First(&pet)
	jsonData, _ := json.Marshal(pet)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "编辑成功",
	})
	return
}
